package com.bjesc_b2c.app.appraiset.mvp.view.activity;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bjesc_b2c.app.appraiset.R;
import com.bjesc_b2c.app.appraiset.RequestAndResultCode;
import com.bjesc_b2c.app.appraiset.base.BaseActivity;
import com.bjesc_b2c.app.appraiset.mvp.presenter.AddCarPresenter;
import com.bjesc_b2c.app.appraiset.mvp.presenter.impl.AddCarPresenterImpl;
import com.bjesc_b2c.app.appraiset.mvp.view.CarIdView;
import com.bjesc_b2c.app.appraiset.utils.CustomSharedPreferences;
import com.bjesc_b2c.app.appraiset.widget.dialog.AnalyseDialog;
import com.orhanobut.logger.Logger;
import com.rxretrofit_build.util.MapUtil;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import master_bean.BasicInfoBean;
import master_bean.DealerBean;
import rxretrofit_base.model.KeyBean;

import static com.bjesc_b2c.app.appraiset.R.id.detectionDate;
import static com.bjesc_b2c.app.appraiset.R.id.edit_analysis;
import static com.bjesc_b2c.app.appraiset.R.id.rela_market_layout;

public class AddCarSourceActivity extends BaseActivity implements CarIdView, AnalyseDialog.DealerDateListener, RadioGroup.OnCheckedChangeListener {

    @InjectView(detectionDate)
    TextView detectionDatTv;
    @InjectView(R.id.tv_dealer_name)
    TextView dealerNameTv;
    @InjectView(R.id.tv_add_dealer)
    TextView daaDealerTv;
    @InjectView(R.id.tv_market_name)
    TextView marketNameTv;
    @InjectView(R.id.edit_dealer_name)
    EditText dealerNameEdit;
    //    @InjectView(R.id.edit_dealer_address)
//    EditText dealerAddressEdit;
    @InjectView(R.id.edit_contact_name)
    EditText bossNameEdit;
    @InjectView(R.id.edit_dealer_phone)
    EditText bossphoneEdit;
    @InjectView(R.id.view_add_derler)
    View adddealerLin;
    @InjectView(R.id.edit_car_vinnum)
    EditText carVinEdit;
    @InjectView(R.id.edit_floor)//楼层
            EditText dealerFloorEdit;
    @InjectView(R.id.edit_house_number)//门牌号
            EditText houseNumberEdit;
    @InjectView(R.id.edit_parking_spaces)//车位数
            EditText parkingSpacesEdit;
    @InjectView(R.id.edit_monthly_sales)//月销量
            EditText monthlySalesEdit;
    @InjectView(R.id.edit_financial)//金融渗透率
            EditText financialEdit;
    @InjectView(R.id.edit_financial_channel)//现有金融渠道
            EditText financialChannelEdit;
    @InjectView(R.id.edit_channel)//收车渠道
            EditText channelEdit;
    @InjectView(R.id.edit_preference)//收车偏好
            EditText preferenceEdit;
    @InjectView(edit_analysis)//商户分析
            EditText analysisEdit;
    @InjectView(R.id.edit_remarks)//备注
            EditText remarksEdit;
    @InjectView(R.id.edit_representative)//业务代表
            EditText representativeEdit;

    //单选布局
    @InjectView(R.id.rg_kanche)
    RadioGroup kancheRg;
    @InjectView(R.id.rg_youxin)
    RadioGroup youxinRg;
    //箭头
    @InjectView(R.id.iv_dealer_info_arrow)
    View carInfoArrowIv;

    private BasicInfoBean infoBean;
    private DealerBean dealerBean;
    private String bossName = "";          //车行联系人姓名
    private String bossPhone = ""; //车行联系人电话
    private String carVin = "";      //车牌vin
    private String dealerAddress = "";//车行详细地址
    private String carForId = "";//车行id
    private String dealerName = "";//车行名
    private String marketId = "";//车市ID
    private String floor = "";//楼层
    private String house_number = "";//门牌号
    private String car_number = "";//车位数
    private String month_sale = "";//月均销量
    private String channel = "";//现有金融渠道
    private String penetration = "";//金融渗透率
    private int kcCombine = 0;//看车是否合作
    private int yxCombine = 0;//优信是否合作
    private String car_preference = "";//收车偏好
    private String car_channel = "";//收车渠道
    private String merchant_analysis = "";//商户分析
    private String description = "";//备注
    private AddCarPresenter carPresenter;
    private AnalyseDialog analyseDialog;
    private int changeCase;
    private String srString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_car_source);
        ButterKnife.inject(this);
        carPresenter = new AddCarPresenterImpl(this);
        kancheRg.setOnCheckedChangeListener(this);
        youxinRg.setOnCheckedChangeListener(this);

//给需要的文本框添加TextChangedListener方法
        carVinEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                // 将输入的小写字母实时转换成大写
                if (changeCase == 0) {
                    srString = s.toString().toUpperCase();
                    if (s.toString().equals("")) {
                        changeCase = 0;
                    } else {
                        changeCase = 1;
                    }
                    s.clear();
                } else if (changeCase == 1) {
                    changeCase = 2;
                    s.append(srString);
                } else {
                    changeCase = 0;
                }
            }
        });
    }

    @OnClick({R.id.btn_detection, R.id.rlty_add_dealer, R.id.rl_return, R.id.rlty_dealer_name,
            R.id.tv_add_dealer, R.id.tv_vinnum_sort, rela_market_layout})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_detection://开始检测
                carPresenter.requestAddCarId(putInfo());
                break;
            case R.id.rlty_dealer_name://选择车源
                Intent intent = new Intent(AddCarSourceActivity.this, MarketActivity.class);
                intent.putExtra("TYPE", 2);
                startIntent(intent, RequestAndResultCode.BasicActivity_To_CarFromActivity);
                break;
            case R.id.rlty_add_dealer://
                if (adddealerLin.getVisibility() == View.VISIBLE) {
                    adddealerLin.setVisibility(View.GONE);
                    setTowardsBottomToTopTextDrawable(carInfoArrowIv);
                } else {
                    adddealerLin.setVisibility(View.VISIBLE);
                    setTowardsTopToBottomTextDrawable(carInfoArrowIv);
                }
                break;
            case R.id.rela_market_layout://选择车市
                startIntent(new Intent(AddCarSourceActivity.this, MarketActivity.class), RequestAndResultCode.BasicActivity_To_SelectColorActivity);
                break;

            case R.id.tv_add_dealer://添加车行
                getAllEditText();
                if (!TextUtils.isEmpty(dealerNameEdit.getText().toString())) {
                    analyseDialog = new AnalyseDialog(AddCarSourceActivity.this, setDealer(), AnalyseDialog.TYPE_DEALER, this);
                } else {
                    showToast("车商名不能为空");
                }
                break;
            case R.id.tv_vinnum_sort:       //排重
                if (!TextUtils.isEmpty(carVinEdit.getText().toString())) {
                    if (carVinEdit.getText().toString().length() == 17) {
                        analyseDialog = new AnalyseDialog(AddCarSourceActivity.this,
                                carVinEdit.getText().toString(), AnalyseDialog.TYPE_VIN);
                    } else {
                        showToast("VIN号码错误");
                    }
                } else {
                    showToast("VIN号码不能为空");
                }
                break;
            case R.id.rl_return:
                finish();
                break;
        }
    }

    private void getAllEditText() {
        dealerName = dealerNameEdit.getText().toString();
//        dealerAddress = dealerAddressEdit.getText().toString();
        bossName = bossNameEdit.getText().toString();
        bossPhone = bossphoneEdit.getText().toString();
        floor = dealerFloorEdit.getText().toString();//楼层
        house_number = houseNumberEdit.getText().toString();//门牌号
        car_number = parkingSpacesEdit.getText().toString();//车位数
        month_sale = monthlySalesEdit.getText().toString();//月均销量
        channel = financialChannelEdit.getText().toString();//现有金融渠道
        penetration = financialEdit.getText().toString();//金融渗透率
        car_preference = preferenceEdit.getText().toString();//收车偏好
        car_channel = channelEdit.getText().toString();//收车渠道
        merchant_analysis = analysisEdit.getText().toString();//商户分析
        description = remarksEdit.getText().toString();//备注
    }

    private DealerBean setDealer() {
        if (dealerBean == null) {
            dealerBean = new DealerBean();
        }
        dealerBean.setDealerName(dealerName);
        dealerBean.setBoss(bossName);
        dealerBean.setPhone(bossPhone);
        dealerBean.setAddress(dealerAddress);
        dealerBean.setXin_che(yxCombine);
        dealerBean.setKan_che(kcCombine);
        dealerBean.setMarket_id(marketId);
        dealerBean.setFloor(floor);
        dealerBean.setHouse_number(house_number);
        dealerBean.setCar_number(car_number);
        dealerBean.setMonth_sale(month_sale);
        dealerBean.setFinancial_penetration(penetration);
        dealerBean.setFinancial_channel(channel);
        dealerBean.setCar_channel(car_channel);
        dealerBean.setCar_preference(car_preference);
        dealerBean.setMerchant_analysis(merchant_analysis);
        dealerBean.setDescription(description);
        return dealerBean;
    }

    private BasicInfoBean putInfo() {
        if (infoBean == null) {
            infoBean = new BasicInfoBean();
        }
        carVin = carVinEdit.getText().toString();
        infoBean.setVin_number(carVin);
        Logger.d("carForId==" + carForId);
        infoBean.setCheck_area_id(carForId);
        return infoBean;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case RequestAndResultCode.CarFromActivity_ResultCode:  //车辆来源
                carForId = data.getStringExtra("carFofId");
                Logger.d("carFofId" + carForId);
                if (!TextUtils.isEmpty(data.getStringExtra("carForName"))) {
                    dealerNameTv.setText(data.getStringExtra("carForName"));
                }
                break;
            case RequestAndResultCode.SelectColorActivity_ResultCode:  //车市
                marketId = data.getStringExtra("marketId");
                if (!TextUtils.isEmpty(data.getStringExtra("marketName"))) {
                    marketNameTv.setText(data.getStringExtra("marketName"));
                }
                break;
        }
    }

    @Override
    public void getCarId(BasicInfoBean bean) {
        Logger.d("车源id----》" + bean.getId());
        infoBean.setId(bean.getId());
        CustomSharedPreferences.saveString(AddCarSourceActivity.this, new MapUtil().put(KeyBean.CARID.valueOf(), bean.getId()).build(), KeyBean.FILE_NAME.valueOf());
        Intent intent = new Intent(AddCarSourceActivity.this, BasicInfoActivity.class);
//      intent.putExtra("BasicInfo",infoBean);
        startIntent(intent, true);

    }

    @Override
    public void getDealerDate(String id) {
        carForId = id;
        dealerNameTv.setText(dealerNameEdit.getText().toString());
        adddealerLin.setVisibility(View.GONE);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        switch (group.getId()) {
            case R.id.rg_kanche:
                kancheCheck(checkedId);
                break;
            case R.id.rg_youxin:
                youxinCheck(checkedId);
                break;
        }
    }

    private void kancheCheck(int checkedId) {
        switch (checkedId) {
            case R.id.rbtn_kx_yes:
                kcCombine = 2;
                break;
            case R.id.rbtn_kx_no:
                kcCombine = 3;
                break;
        }
    }

    private void youxinCheck(int checkedId) {
        switch (checkedId) {
            case R.id.rbtn_yx_yes:
                yxCombine = 2;
                break;
            case R.id.rbtn_yx_no:
                yxCombine = 3;
                break;
        }
    }
    //声明两个变量，在控制输入小写显示大写的时候用到

    /**
     * 箭头动画，上转下
     */
    private void setTowardsTopToBottomTextDrawable(View view) {
        ObjectAnimator oa = ObjectAnimator.ofFloat(view, "rotation", 0f, 180f);
        oa.setDuration(200);
        oa.start();
    }

    /**
     * 箭头动画，下转上
     */
    private void setTowardsBottomToTopTextDrawable(View view) {
        ObjectAnimator oa = ObjectAnimator.ofFloat(view, "rotation", 180f, 0f);
        oa.setDuration(200);
        oa.start();
    }

    /**
     * 设置车辆信息、手续信息、配置信息点击后的背景颜色为灰色
     *
     * @param v
     */
    private void changeBackgroundToGray(View v) {
        v.setBackgroundResource(R.color.bg);
    }

    /**
     * 设置车辆信息、手续信息、配置信息点击后的背景颜色为白色
     *
     * @param v
     */
    private void changeBackgroundToWhite(View v) {
        v.setBackgroundResource(R.color.colorWhite);
    }
}
